# 测试某些tf函数
import math

import numpy as np
import tensorflow as tf

# 求张量运算的梯度（函数求导）
x = tf.Variable(initial_value=math.pi / 2)
with tf.GradientTape() as tape:
    y = tf.sin(x)
    print(y)
    dy_dx = tape.gradient(y, x)
    assert dy_dx == tf.cos(x)

# 求二阶梯度
# v=dl/dt a=dv/dt
t = tf.Variable(initial_value=1.)
with tf.GradientTape() as outer_tape:
    with tf.GradientTape() as inner_tape:
        l = 4.9 * t ** 2
        v = outer_tape.gradient(l, t)
        a = inner_tape.gradient(v, t)
        print(f'重力加速度={a}')

# 测试方法
num_one = tf.Variable(initial_value=1.)
num_one.assign_sub(0.5)
print(num_one)

# 求导数
x = tf.Variable(initial_value=1.0)

with tf.GradientTape() as tape:
    y = tf.square(x)
    grad_y_x = tape.gradient(y, x)
    print(f'grad_y_x={grad_y_x}')

# ==
arr1 = np.array([1, 2, 3])
arr2 = np.array([1, 2, 1])
matches = arr1 == arr2
print(matches)
assert isinstance(matches,np.ndarray)
print(f'matches.mean()={matches.mean()}')
print(np.count_nonzero(matches))

last_predictions = np.array([0.1,0.2,0.5,0.7])
zero_or_ones = np.array([1 if p > 0.5 else 0 for p in last_predictions])
print(f'zero_or_ones={zero_or_ones}')